import Axios from 'axios';
import { updateToken } from './userApi';

const instance = Axios.create({ withCredentials: false });

let updateCount = 0;

instance.interceptors.response.use(function (response) {
    return response.data
}, function (error) {
    if (error.response.status === 401 || error.response.status === 403) {
        updateCount++;
        if (updateCount > 10)  {
            localStorage.removeItem('token');
            window.location.reload();
            return;
        }
        // token 固定1小时过期，自动更新
        updateToken().then(data => {
            localStorage.setItem('token',  'Bearer ' + data);
        }).catch(err => {
            if (err.response.status === 401 || err.response.status === 403) {
                localStorage.removeItem('token');
                window.location.reload();
            }
        });
    }
    return Promise.reject(error);
});

export default instance